package com.gi.profiler.utils;

import java.lang.reflect.Field;

import android.database.Cursor;
import android.media.RingtoneManager;
import android.net.Uri;
import android.util.Log;

import com.gi.profiler.ProfilerApplication;
import com.gi.profiler.R;

/**
 * The Class Utility.
 */
public class Utility {
    private static final String LOG_NAME = Utility.class.getName();


    /**
     * Gets the drawable id by name.
     * Faster than using Resources.getIdentifier() as long as you are retrieving
     * data from your application's own R.java
     * 
     * @param imgName
     *            the img name without extension
     * @return the drawable id by name
     */
    public static int getDrawableIdByName(String imgName) {
	int drawableId = -1;
	try {
	    Class res = R.drawable.class;
	    Field field = res.getField(imgName);
	    drawableId = field.getInt(null);
	} catch (Exception e) {
	    Log.e(LOG_NAME, "Failure to get drawable id.", e);
	}

	return drawableId;
    }
    
    /**
     * 
     * @param soundType : like RingtoneManager.TYPE_ALARM
     * @return
     */
    public static Uri[] getAvailableTonesForSoundType(int soundType){
	RingtoneManager ringtoneMgr = new RingtoneManager(ProfilerApplication.getAppContext());
	ringtoneMgr.setType(soundType);
	Cursor alarmsCursor = ringtoneMgr.getCursor();
	int alarmsCount = alarmsCursor.getCount();
	if (alarmsCount == 0 && !alarmsCursor.moveToFirst()) {
	    return null;
	}
	Uri[] alarms = new Uri[alarmsCount];
	while(!alarmsCursor.isAfterLast() && alarmsCursor.moveToNext()) {
	    int currentPosition = alarmsCursor.getPosition();
	    alarms[currentPosition] = ringtoneMgr.getRingtoneUri(currentPosition);
	}
	alarmsCursor.close();
	return alarms;
    }
}
